﻿using System.Runtime.InteropServices;

namespace System.IO
{
    /// <summary>
    /// 二进制文件格式读取的基类
    /// </summary>
    public class FileReader : IDisposable
    {
        /// <summary>
        /// 文件基础信息
        /// </summary>
        public FileInfo FileInfo;

        /// <summary>
        /// 用以读取数据的二进制流文件
        /// </summary>
        protected BinaryReader _BinaryReader;

        public FileReader(string FileFullName)
        {
            if (File.Exists(FileFullName))
            {
                FileInfo = new FileInfo(FileFullName);
                _BinaryReader = new BinaryReader(File.Open(FileInfo.FullName, FileMode.Open));
            }
            else
            {
                Console.WriteLine(string.Format("{0} get {0} is not exist.", GetType().Name,FileFullName));
            }
            
        }

        public virtual void Dispose()
        {
            if (FileInfo != null)
            {
                FileInfo = null;
            }
            if (_BinaryReader != null)
            {
                //Netframe = 3.5时无法调用Dispose，使用Close替代
                //_BinaryReader.Dispose();

                _BinaryReader.Close();

                _BinaryReader = null;
            }
        }

        ~FileReader()
        {
            Dispose();
        }


        public virtual T Read<T>(int StartIndex = -1)
        {
            if(_BinaryReader==null)
            {
                Console.WriteLine(string.Format("{0} _BinaryReader is null.",GetType().Name));
                return default(T);
            }
            
            int size = Marshal.SizeOf(typeof(T));
            byte[] RawData = Read(size, StartIndex);
            return BytesTools.BytesTo<T>(RawData);
        }

        public virtual byte[] Read(int Size, int StartIndex=-1)
        {
            if (_BinaryReader == null)
            {
                Console.WriteLine(string.Format("{0} _BinaryReader is null.", GetType().Name));
                return null;
            }

            _BinaryReader.BaseStream.Position = StartIndex > 0 ? StartIndex : _BinaryReader.BaseStream.Position;
            byte[] RawData = _BinaryReader.ReadBytes(Size);
            return RawData;
        }
    }
}
